package com.csea.tools.controller.mp;

import com.csea.tools.config.wechat.mp.WechatMpAccountConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author Csea
 * @title
 * @date 2019/12/26 20:45
 */
@Controller
@RequestMapping("/mp")
@Api(description = "微信公众号获取用户信息")
@Slf4j
public class MpAuthorizationController {
    @Autowired
    private WechatMpAccountConfig accountConfig;
    @Autowired
    private WxMpService wxMpService;

    @ApiOperation(value = "前端输入最终拿到用户信息时要返回的完整页面地址", notes = "注意：需要完整地址")
    @ApiImplicitParam(name = "returnUrl", value = "完整的url地址", required = true)
    @GetMapping("/url")
    public String authorization(String returnUrl) {
        String url = accountConfig.getRedirectUrl();
        String redirectUrl = null;
        try {
            redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "redirect:" + redirectUrl;
    }

    @ApiOperation(value = "获取用户信息", notes = "这是/url接口要重定向过来获取用户信息的地址，前端不要测试")
    @GetMapping("/userinfo")
    public String userinfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        boolean valid = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
        log.info("valid: {}", valid);
        try {
            if (valid) {
                wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
            }
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);

            return "redirect:" + returnUrl + "?openId=" + wxMpUser.getOpenId();
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("微信网页授权失败：{}", e.getError());
        }
        return "redirect:" + returnUrl;
    }
}
